#This script plots the bootstrap distributions and summary statistics for the main results
#It produces Figure G2 in the paper
library(ggplot2)
library(dplyr)
library(purrr)
library(ggthemes)
library(cowplot)

# Define the list of countries and the version string (modify as needed)
countries <- c("djazairess", "maghress", "masress", "sauress", "turess")
version <- "150000030k"  # adjust to match the naming in your files

# Load each country's CI summary and add a country identifier
stats_list <- lapply(countries, function(country) {
  file_path <- paste0("data/output/cos_sims_bootstrap/", country, "/stats_summary_", version, ".rds")
  df <- readRDS(file_path)
  df$country <- country
  return(df)
})

all_stats <- bind_rows(stats_list)

# Convert group to Date if needed (adjust format accordingly)
all_stats <- all_stats %>%
  mutate(date = as.Date(group, format = "%Y-%m-%d"),
         # Set the desired order: here masress and turess first, then the others
         country = factor(country, levels = c("masress", "turess", "djazairess", "maghress", "sauress"))
  )

g2 <- all_stats %>%
  ggplot(aes(x = date, y = mean)) +
  geom_point(color = "black", size = 2, alpha = .1) +
  geom_errorbar(aes(ymin = mean - se, ymax = mean + se), width = 0.2, color = "gray", alpha = .5) +
  # You can also add error bars for the CI if desired:
  # geom_errorbar(aes(ymin = lower_ci, ymax = upper_ci), width = 0.2, color = "gray", alpha = .5) +
  geom_smooth(
    method = "loess",
    size = 1,
    span = .5,
    fill = "white",
    col = "black",
    alpha = .5
  ) +
  theme_tufte(base_family = "Helvetica") +
  labs(x = "Year-week",
       y = "Cosine similarity, leaders : opposition index") +
  ylim(-.2, 0.2) +
  theme(
    legend.position = "right",
    axis.text.x = element_text(size = 20),
    axis.text.y = element_text(size = 20),
    axis.title.x = element_text(size = 15),
    axis.title.y = element_text(size = 15),
    legend.text = element_text(size = 15),
    legend.title = element_text(size = 20),
    panel.border = element_rect(colour = "black", fill = NA, size = 1),
    plot.background = element_rect(fill = "white", colour = NA),
    strip.text = element_text(size = 20)
  ) +
  facet_wrap( ~ country, ncol = 5)

png(
  "plots/figG2.png",
  width = 750,
  height = 150,
  units = 'mm',
  res = 300
)
plot_grid(g2, ncol = 1, nrow = 1, labels = "AUTO")
dev.off()
